package com.jdk.mode.relate;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author jukg
 * @date 2023/08/28 15:07
 * @description 观察者模式，被观察者有变动，所有观察者有所感知   公众号消息 被观察者， 微信 观察者
 */
public class ObserveTest {


    public static void main(String[] args) {
        Subject subject = new SubjectImpl();

        Observe o1 = new ObserveUser("o1");
        Observe o2 = new ObserveUser("o2");
        Observe o3 = new ObserveUser("o3");
        subject.register(o1);
        subject.register(o2);
        subject.register(o3);
        subject.register(o1);
        subject.notifyObserve("第一条消息");
        Observe o4 = new ObserveUser("o4");
        subject.register(o4);
        subject.notifyObserve("第二条消息");
    }



}

interface Subject{
    void register(Observe observe);

    void remove(Observe observe);

    void notifyObserve(String msg);
}

class SubjectImpl implements Subject{

    private List<Observe> list ;

    public SubjectImpl() {
        this.list = new ArrayList<>();
    }

    @Override
    public void register(Observe observe) {
        if(!this.list.contains(observe)){
            this.list.add(observe);
        }
    }

    @Override
    public void remove(Observe observe) {
        if(this.list.contains(observe)){
            this.list.remove(observe);
        }
    }

    @Override
    public void notifyObserve(String msg) {
        if(!this.list.isEmpty()){
            for(Observe observe: list){
                observe.update(msg);
            }
        }
    }
}

abstract class Observe{
    private String name;

    public Observe(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    abstract void update(String msg);
}

class ObserveUser extends Observe{

    public ObserveUser(String name) {
        super(name);
    }

    @Override
    void update(String msg) {
        System.out.println(super.getName()+"接收到消息：" + msg);
    }
}

